/*
 * @Author: your name
 * @Date: 2021-07-18 10:32:41
 * @LastEditTime: 2021-07-27 15:02:59
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \geek-client-mobile\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
Vue.use(VueRouter)

const Tabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const User = () => import('@/views/user')
const Article = () => import('@/views/article')
const Login = () => import('@/views/login')
const UserProfile = () => import('@/views/user/profile')
const UserChat = () => import('@/views/user/chat')

const routes = [
  // 路由规则
  { path: '/', components: { default: Home, tabbar: Tabbar } },
  { path: '/question', components: { default: Question, tabbar: Tabbar } },
  { path: '/video', components: { default: Video, tabbar: Tabbar } },
  { path: '/user', components: { default: User, tabbar: Tabbar } },
  { path: '/article', component: Article },
  { path: '/login', component: Login },
  { path: '/user/profile', component: UserProfile },
  { path: '/user/chat', component: UserChat }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 1. 当你没有token的时候，去访问/user开头的路由，统统去登录（带上访问的路由地址）
  // 2. 其他清空一概放行
  const token = store.state.user.token
  if (!token && to.path.startsWith('/user')) {
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath))
  }
  // 放行
  next()
})

export default router
